package com.springboot.blog.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.springboot.blog.beans.*;
import com.springboot.blog.config.utils.ImgStr;
import com.springboot.blog.config.utils.R;
import com.springboot.blog.dao.BlogDao;
import com.springboot.blog.dao.BlogSetDao;
import com.springboot.blog.dao.ClassifyDao;
import com.springboot.blog.dao.CommentDao;
import com.springboot.blog.service.BlogService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
public class BlogIndexController {

    @Resource
    private BlogService blogService;
    @Resource
    private BlogDao blogDao;
    @Resource
    private CommentDao commentDao;
    @Resource
    private BlogSetDao blogSetDao;
    @Resource
    private ClassifyDao classifyDao;
    @Resource
    private RedisTemplate<Object,Object> redisTemplate;


    @RequestMapping("index/blogindex")
    @ResponseBody
    public JSON blogindex(Model model, @RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10")String limit){
        //设置 redisTemplate 对象 key 的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        PageBlog<Blog> page1 = blogService.pages(Integer.parseInt(page), Integer.parseInt(limit));
        Integer integer = (Integer) redisTemplate.opsForValue().get("allBlog");

        //判断是否为空
        if (null == integer) {
            //去数据库查询，并存放到 redis 缓存中
            integer = blogDao.queryStaCount();
            redisTemplate.opsForValue().set("allBlog",integer,30, TimeUnit.SECONDS);
        }
        List<Blog> list = new ArrayList<>();
        for (Blog blog : page1.getItems()){
            String blogContent = blog.getBlogContent();
            List<String> imgStr = ImgStr.getImgStr(blogContent);
            for (String ss:imgStr){
                blog.setImages(ss);//获取富文本链接
            }
            if (blog.getImages()==null){
                blog.setImages("https://s3.ax1x.com/2021/01/28/y9konJ.jpg");
            }
            list.add(blog);
        }
        model.addAttribute("news",list);
        JSONObject json = new JSONObject();
        json.put("data",list);
        json.put("count", integer);
        json.put("status", 200);
        return json;
    }

    @RequestMapping("index/indexinfo/{blogId}")
    public String indexinfo(Model model,@PathVariable String blogId){
        blogDao.updateView(Integer.parseInt(blogId));
        Blog blog = new Blog();
        blog.setBlogId(Integer.parseInt(blogId));
        Blog blog1 = blogDao.selectById(blog);
        model.addAttribute("info",blog1);
        List<BlogComment> blogComment = commentDao.findBlogComment(blogId);
        model.addAttribute("blogComments",blogComment);

        List<BlogSet> blogSets = blogSetDao.selectList(null);
        model.addAttribute("index",blogSets);

        List<Blog> blogList = blogDao.selectAllBlog();
        model.addAttribute("blogList",blogList);
        int contentByIdCount = commentDao.contentByIdCount(blogId);
        model.addAttribute("contentComment",contentByIdCount);
        return "detail";
    }

    @RequestMapping("index/indexcomment")
    @ResponseBody
    public R indexcomment(String blogid, String nickname, String email, String commentcontent){
        BlogComment comment = new BlogComment();
        comment.setBlogId(Long.parseLong(blogid));
        comment.setCommentName(nickname);
        comment.setCommentEmail(email);
        comment.setCommentContent(commentcontent);
        comment.setCommentStatus(1);
        int insert = commentDao.insert(comment);
        if (insert>0){
            return R.ok();
        }
        return R.error();
    }

    @RequestMapping("view/indexclass/{blogClassifyId}")
    public String indexclass(Model model,HttpServletRequest request, @PathVariable String blogClassifyId){
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
        request.getSession().setAttribute("blogClassifyId",blogClassifyId);
        List<BlogSet> blogSets = (List<BlogSet>) redisTemplate.opsForValue().get("blogSets");
        if (null== blogSets ){
            blogSets = blogSetDao.selectList(null);
            redisTemplate.opsForValue().set("blogSets",blogSets,30, TimeUnit.SECONDS);
        }
        model.addAttribute("index",blogSets);
        List<Blog> blogList = (List<Blog>) redisTemplate.opsForValue().get("blogList");
        if (null==blogList){
            blogList = blogDao.selectAllBlog();
            redisTemplate.opsForValue().set("blogList",blogList,30, TimeUnit.SECONDS);
        }
        model.addAttribute("blogList",blogList);
        List<BlogClassify> blogClassifies = (List<BlogClassify>) redisTemplate.opsForValue().get("blogClassifies");
        if (null == blogClassifies){
            blogClassifies = classifyDao.selectList(null);
            redisTemplate.opsForValue().set("blogClassifies",blogClassifies,30, TimeUnit.SECONDS);
        }
        model.addAttribute("blogClassifies",blogClassifies);
        return "view/index";
    }

    @RequestMapping("index/blogindexclass")
    @ResponseBody
    public String blogindexclass(Model model,HttpServletRequest request, @RequestParam(defaultValue = "1") String page,  @RequestParam(defaultValue = "10")String limit){
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
        String  blogClassifyId = (String) request.getSession().getAttribute("blogClassifyId");

        PageBlog<Blog> page1 = (PageBlog<Blog>) redisTemplate.opsForValue().get("page2");
        if (null == page1){
            page1 = blogService.pageclass(Integer.parseInt(page), Integer.parseInt(limit),Integer.parseInt(blogClassifyId));
            redisTemplate.opsForValue().set("page2",page1,30, TimeUnit.SECONDS);
        }

        Integer integer = (Integer) redisTemplate.opsForValue().get("integer1");
        if (null == integer){
            integer = blogDao.queryclassCount(Integer.parseInt(blogClassifyId));
            redisTemplate.opsForValue().set("integer1",integer,30, TimeUnit.SECONDS);
        }
        List<Blog> list = new ArrayList<>();
        for (Blog blog : page1.getItems()){
            String blogContent = blog.getBlogContent();
            List<String> imgStr = ImgStr.getImgStr(blogContent);
            for (String ss:imgStr){
                blog.setImages(ss);//获取富文本链接
            }
            if (blog.getImages()==null){
                blog.setImages("https://s3.ax1x.com/2021/01/28/y9konJ.jpg");
            }
            list.add(blog);
        }
        model.addAttribute("news",list);
        JSONObject json = new JSONObject();
        json.put("data",list);
        json.put("count", integer);
        json.put("status", 200);
        return json.toString();
    }
}
